package com.fzd.code.file.storage.cloud.tencent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fzd.code.file.storage.*;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.request.UploadFileRequest;
import com.qcloud.cos.sign.Credentials;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TencentCloudStorageServiceImpl implements IStrorage {
    @Autowired
    private TencentCloudStorageAccountConfig accountConfig;
    @Autowired
    private DefaultUrlRuleParser defaultUrlRuleParser;
    @Autowired
    private DefaultFileNameParser defaultFileNameParser;

    private COSClient client;
    private void init() {
        Credentials credentials = new Credentials(accountConfig.getAppId(), accountConfig.getSecretId(),accountConfig.getSecretKey());
        //初始化客户端配置
        ClientConfig clientConfig = new ClientConfig();
        //设置bucket所在的区域，华南：gz 华北：tj 华东：sh
        clientConfig.setRegion(accountConfig.getRegion());
        client = new COSClient(clientConfig, credentials);
    }


    public void post(StorageConfig storageConfig, Source source) {
        defaultUrlRuleParser.parse(storageConfig,source);
        post(source.getData(),source.getUrl());
    }

    public String post(byte[] data, String path) {
        //腾讯云必需要以"/"开头
        if (!path.startsWith("/")) {
            path = "/" + path;
        }

        //上传到腾讯云
        UploadFileRequest request = new UploadFileRequest(accountConfig.getBucketName(), path, data);
        String response = client.uploadFile(request);

        JSONObject jsonObject = JSON.parseObject(response);
        if (jsonObject.getIntValue("code") != 0) {
            throw new RuntimeException("文件上传失败，" + jsonObject.getString("message"));
        }

        return accountConfig.getDomain() + path;
    }


    public void get(StorageConfig storageConfig, Source source) {

    }


}
